var canvas, ctx;
var vertexes = [];
var diffPt = [];
var autoDiff = 100;
var verNum = 250;
var canvasW = window.innerWidth * 0.332;
var addListener = function(e, str, func) {
  if (e.addEventListener) {
    e.addEventListener(str, func, false);
  } else if (e.attachEvent) {
    e.attachEvent("on" + str, func);
  } else {
  }
};

var resize = function () {
  canvasW = document.getElementById('load-wine-surface-wrapper').offsetWidth * 0.332;
  initCanvas(canvasW, 20);
  var cW = canvas.width;
  var cH = canvas.height;
  for (var i = 0; i < verNum; i++) vertexes[i] = new Vertex(cW / (verNum - 1) * i, cH / 2, cH / 2);
  initDiffPt();
};

var init = function () {
  resize();
  var FPS = 30;
  var interval = 1000 / FPS >> 0;
  addListener(window, "resize", resize);
  setInterval(function () {
    autoDiff = 60;
  }, 1100);
  setInterval(update, interval);
};

var initDiffPt = function () {
  for (var i = 0; i < verNum; i++) diffPt[i] = 0;
};

var xx = 150;
var dd = 15;

var update = function () {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  autoDiff -= autoDiff * 0.9;
  diffPt[xx] = autoDiff;
  
  for (var i = xx - 1; i > 0; i--) {
    var d = xx - i;
    if (d > dd) d = dd;
    diffPt[i] -= (diffPt[i] - diffPt[i + 1]) * (1 - 0.01 * d);
  }
  
  for (var i = xx + 1; i < verNum; i++) {
    var d = i - xx;
    if (d > dd) d = dd;
    diffPt[i] -= (diffPt[i] - diffPt[i - 1]) * (1 - 0.01 * d);
  }

  for (var i = 0; i < vertexes.length; i++) {
    vertexes[i].updateY(diffPt[i]);
  }

  draw();
};

var color1 = "#b30e10";
var color2 = "#de3e25";

var draw = function () {
  ctx.beginPath();
  ctx.moveTo(0, window.innerHeight);
  ctx.fillStyle = color1;
  ctx.lineTo(vertexes[0].x, vertexes[0].y);
  for (var i = 1; i < vertexes.length; i++) {
    ctx.lineTo(vertexes[i].x, vertexes[i].y);
  }
  ctx.lineTo(canvas.width, window.innerHeight);
  ctx.lineTo(0, window.innerHeight);
  ctx.fill();

  ctx.beginPath();
  ctx.moveTo(0, window.innerHeight);
  ctx.fillStyle = color2;
  ctx.lineTo(vertexes[0].x, vertexes[0].y + 3);
  
  for (var i = 1; i < vertexes.length; i++) {
    ctx.lineTo(vertexes[i].x + 15, vertexes[i].y + 5);
  }
  ctx.lineTo(canvas.width, window.innerHeight);
  ctx.lineTo(0, window.innerHeight);
  ctx.fill();
};

var initCanvas = function (width, height) {
  canvas = document.getElementById("load-wine-surface");
  canvas.width = width;
  canvas.height = height;
  ctx = canvas.getContext("2d");
};

var Vertex = function (x, y, baseY) {
  this.baseY = baseY;
  this.x = x;
  this.y = y;
  this.vy = 0;
  this.targetY = 0;
  this.friction = 0.15;
  this.deceleration = 0.95;
};

Vertex.prototype.updateY = function(diffVal) {
  this.targetY = diffVal + this.baseY;
  this.vy += this.targetY - this.y;
  this.y += this.vy * this.friction;
  this.vy *= this.deceleration;
};

/* loading progress */
var loadProgress, loadWine, loadWineSurface;
var currentProgress = 0;
$(document).ready(function () {
  loadProgress = document.getElementById("load-progress");
  loadWine = document.getElementById("load-wine");
  loadWineSurface = document.getElementById("load-wine-surface-wrapper");
});

var wineLowest = 85, wineHighest = 57, wineHeight = wineLowest - wineHighest;
var wineSurfaceLowest = 83, wineSurfaceHighest = 55, wineSurfaceHeight = wineSurfaceLowest - wineSurfaceHighest;

var publishProgress = function () {
  if (currentProgress > 100) {
    return;
  }
  
  loadProgress && (loadProgress.innerHTML = '&nbsp;' + currentProgress + '%');
  loadWine && (loadWine.style.top = wineLowest - wineHeight * currentProgress / 100 + '%');
  loadWineSurface && (loadWineSurface.style.top = wineSurfaceLowest - wineSurfaceHeight * currentProgress / 100 + '%');
  
  ++currentProgress;
};

var picUrls = [
  "img/index-2-1.png",
  "img/index-2-2.png",
  "img/index-2-3.png",
  "img/index-2-4.png",
  "img/index-2-5.png",
  "img/index-2-6.png",
  "img/index-lucky-intro-foot.png",
  "img/pg2-1.png",
  "img/pg2-2.png",
  "img/pg2-3.png",
  "img/pg2-r1.png",
  "img/pg2-r2.png",
  "img/pg2-r3.png",
  "img/pg2-r4.png",
  "img/pg2-r5.png",
  "img/pg2-r6.png",
  "img/pg2-r7.png",
  "img/pg2-r8.png",
  "img/pg2-r9.png",
  "img/pg2-xj.png",
  "img/pg2-xjhg.png",
  "img/pg2-zb.png",
  "img/index-lucky-intro-angle.png",
  "img/pg3-hb.png",
  "img/pg3-bm.png",
  "img/pg3-xm.png",
  "img/pg3-en.png",
  "img/index-blackboard-people.png",
  "img/rank-title.png",
  "img/food-root.png",
  "img/rank-title.png",
  "img/food-foot.png",
  "img/rank-title.png",
  "img/food-root.png",
  "img/rule-1.png",
  "img/rule-2.png",
  "img/rule-3.png",
  "img/rule-4.png"
];
var wrappers = [
  "#index-intro-head", "#index-intro-head-people", "#index-intro-head-msg-one", "#index-intro-head-msg-two", "#index-intro-foot", "#index-intro-foot-btn",
   "#index-lucky-intro-foot", "#pg2-1","#pg2-2","#pg2-3","#pg2-r1","#pg2-r2","#pg2-r3","#pg2-r4","#pg2-r5","#pg2-r6","#pg2-r7","#pg2-r8","#pg2-r9","#pg2-xj","#pg2-xjhg","#pg2-zb","#index-lucky-intro-angle",
   "#pg3-hb", "#pg3-bm", "#pg3-xm","#pg3-en","#index-blackboard-people",
  "#food-title-wrapper", "#food-foot-wrapper", "#rank-title-wrapper", "#rank-foot-wrapper", "#rule-title-wrapper","#rule-foot-wrapper",
  "#rule-1-wrapper", "#rule-2-wrapper", "#rule-3-wrapper", "#rule-4-wrapper"];
var anims = [
  'class="ani" swiper-animate-effect="fadeInDown" swiper-animate-duration="0.5s"',
  'class="ani zoom" swiper-animate-effect="bounceInLeft" swiper-animate-duration="1s" swiper-animate-delay="0.5s"',
  'class="ani head-msg-one" swiper-animate-effect="bounceIn" swiper-animate-duration="2.4s" swiper-animate-delay="1.3s"',
  'class="ani" swiper-animate-effect="fadeInDown" swiper-animate-duration="0.5s" swiper-animate-delay="2.1s"',
  'class="ani" swiper-animate-effect="fadeInUp" swiper-animate-duration="0.5s" swiper-animate-delay="2.6s"',
  'class="ani updown" swiper-animate-effect="fadeInUp" swiper-animate-duration="1s" swiper-animate-delay="2.9s"',
  'class="ani" swiper-animate-effect="fadeInUp" swiper-animate-duration="0.5s" swiper-animate-delay="3.7s"',
  'class="ani" swiper-animate-effect="zoomInDown" swiper-animate-duration="0.3s" swiper-animate-delay="0.1s"',
  'class="ani" swiper-animate-effect="fadeOut" swiper-animate-duration="0.1s" swiper-animate-delay="3.5s"',
  'class="ani" swiper-animate-effect="bounceInLeft" swiper-animate-duration="0.3s" swiper-animate-delay="0.8s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.2s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.4s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.6s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.8s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.8s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.6s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.4s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="2.2s"',
  'class="ani" swiper-animate-effect="zoomIn" swiper-animate-duration="0.3s" swiper-animate-delay="3s"',
  'class="ani" swiper-animate-effect="bounceInDown" swiper-animate-duration="0.8s" swiper-animate-delay="3.9s"',
  'class="ani" swiper-animate-effect="fadeIn" swiper-animate-duration="0.3s" swiper-animate-delay="1.8s"',
  'class="ani updown" swiper-animate-effect="fadeInUp" swiper-animate-duration="1s" swiper-animate-delay="3.6s"',
  'class="ani" swiper-animate-effect="zoomInDown" swiper-animate-duration="1s" swiper-animate-delay="0.2s"',
  'class="ani" swiper-animate-effect="fadeInLeft" swiper-animate-duration="1s" swiper-animate-delay="0.7s"',
  'class="ani" swiper-animate-effect="fadeInRight" swiper-animate-duration="1s" swiper-animate-delay="0.7s"',
  'class="ani pg3-en" swiper-animate-effect="bounceIn" swiper-animate-duration="2s" swiper-animate-delay="2.3s"',
  'class="ani" swiper-animate-effect="bounceInLeft" swiper-animate-duration="1s" swiper-animate-delay="1.7s"',
  '', '', '', '', '', '' , '', '', '', ''  
];
var loaded = 0, total = picUrls.length, current = 0;
var loadingInterval = null;
var loadedPageOneImgCount = 0, pageOneImgTotal = 6;

var loadedPageOneImg = function () {
  ++loadedPageOneImgCount;
  if (loadedPageOneImgCount >= pageOneImgTotal) {
    loadOthers();
  }
};

var swiper = null;

/**
 * Loaded one img completely
 * Update the loading progress
 *
 * @param {DOM} - img The loaded img DOM Element
 */
var oneImgLoadComplete = function (img, index) {
    // Clear fake loading interval if it exists
    loadingInterval && clearInterval(loadingInterval);
    
    if (img) {
      loaded += 1;
      $(wrappers[index]).append(img);
    }

    if (loaded >= total) { // Has finished all loading tasks
      loadingInterval && clearInterval(loadingInterval);
      var mid = 100;
      loadingInterval = setInterval(function () {
        if (currentProgress < mid) {
          currentProgress += 1;
          publishProgress();
        } else {
          currentProgress = 100;
          publishProgress();
          loadingInterval && clearInterval(loadingInterval);
          swiper = new Swiper('.swiper-container', {
            direction: 'vertical',
            mousewheelControl: true,
            watchSlidesProgress: true,
            onInit: function (swiper) {
              swiperAnimateCache(swiper); // 隐藏动画元素 
            },
            onSlideChangeEnd: function (swiper) { 
              swiperAnimate(swiper); // 每个slide切换结束时也运行当前slide动画
            }
          });
          setTimeout(function () { swiper.slideTo(1); }, 100);
        }
      }, 100);
    } else { // Successfully loaded some img
      // Start a fake loading progress
      var next = Math.floor((loaded + 1) / total * 100);
      var last = Math.floor(loaded / total * 100);
      var mid = (last + next) / 2;
      loadingInterval = setInterval(function () {
        if (currentProgress < mid) {
          currentProgress += 1;
          publishProgress();
        } else {
          loadingInterval && clearInterval(loadingInterval);
        }
      }, 100);
    }
};

/**
 * Occur error when load img
 * Just ignore it
 */
var oneImgLoadError = function () {
    // Call load complete method to update the loading progress
    oneImgLoadComplete();
};

var loadOthers = function () {
  for (var i = 0; i < total; ++i) {
    var img = $('<img src="' + picUrls[i] + '" onload="oneImgLoadComplete(this, ' + i + ')" onerror="oneImgLoadError()" ' + anims[i] + '>');
  }
  oneImgLoadComplete();
};

var loadPageOneImgError = function () {
  alert('加载失败，请刷新重试');
};

/**
 * init status of code button
 */
var initCodeBtnStatus = function (btn) {
  if (!btn) {
    return;
  }
  
  var diff = getSendCodeDiff();
  diff = Math.floor(diff / 1000);
  if (canSendCode(diff)) {
    enableBtn(btn);
  } else {
    disableBtn(btn);
    setCodeBtnStatus(btn, 60 - diff);
  }
};

/** Set code button status */
var setCodeBtnStatusTimeout = null;
var setCodeBtnStatus = function (btn, rest) {
  if (rest <= 0) {
    // no time left, can send code again
    enableBtn(btn);
    $(btn).val('点击获取报名验证码');
  } else {
    // must to wait until the rest time past
    $(btn).val(rest + '秒后可以重新获取');
    // run this method again after 1 second
    setCodeBtnStatusTimeout = setTimeout(function () {
      setCodeBtnStatus(btn, rest - 1);
    }, 1000);
  }
};

/** Try to send code */
var sendCode = function (btn) {
  // no weixin userinfo found
  if (!userInfoObj || !userInfoObj.openid) {
    errToast($('#err-toast'), $('#err-toast-content'), '缺少微信账号信息，请刷新重试');
    return;
  }
  var diff = getSendCodeDiff();
  diff = Math.floor(diff / 1000);
  if (canSendCode(diff)) {
    // check photo format
    var phone = $.trim($('#register-tel').val());
    if (phone == '') {
      errToast($('#err-toast'), $('#err-toast-content'), '请输入手机号');
    } else if (!/^1[0-9]{10}$/.test(phone)) {
      errToast($('#err-toast'), $('#err-toast-content'), '请输入合法的11位手机号');
    } else {
      disableBtn(btn);
      setCodeBtnStatus(btn, 60);
      
      // store the last time of code-sending
      utils.setCookie(COOKIE_KEY_LAST_SEND_CODE_TIME, new Date().getTime(), 1);
      
      // request the server to send code to phone
      $.ajax({
        type: 'get',
        url: 'sendcode',
        data: { phone: phone, openId: userInfoObj.openid },
        success: function (data) {
          try {
            var dataObj = JSON.parse(data);
            if (dataObj.code == 0) {
              // success
              successToast($('#success-toast'), $('#success-toast-content'), '验证码发送成功');
            } else if (dataObj.body && dataObj.body.exists) {
              // exists, redirect to lucky.html
              successToast($('#success-toast'), $('#success-toast-content'), dataObj.msg);
              
                setTimeout(function () {
                  location.href = 'lucky.html?openid=' + userInfoObj.openid;
                }, 2000);
                // no need to send code, redirect directly, the cookie can be cleared
                utils.deleteCookie(COOKIE_KEY_LAST_SEND_CODE_TIME);
                enableBtn(btn);
                setCodeBtnStatusTimeout && clearTimeout(setCodeBtnStatusTimeout);
               setCodeBtnStatus(btn, 0);              
             
            } else {
              // error
              sendCodeError(btn, dataObj.msg);
            }
          } catch (e) {
            sendCodeError(btn, JSON.stringify(e));
          }
        },
        error: function (data, textStatus) {
          sendCodeError(btn, textStatus || data.statusText);
        }
      });
    }
  } else {
    disableBtn(btn);
    setCodeBtnStatus(btn, diff);
  }
  return false;
};

/** Send code error */
var sendCodeError = function (btn, msg) {
  utils.deleteCookie(COOKIE_KEY_LAST_SEND_CODE_TIME);
  enableBtn(btn);
  setCodeBtnStatusTimeout && clearTimeout(setCodeBtnStatusTimeout);
  setCodeBtnStatus(btn, 0);
  errToast($('#err-toast'), $('#err-toast-content'), msg);
};

var disableBtn = function (btn) {
  $(btn).attr("disabled", "true");
  $(btn).addClass('disable');
};

var enableBtn = function (btn) {
  $(btn).removeAttr("disabled");
  $(btn).removeClass('disable');
};

/** Cookie key, last send code time */
var COOKIE_KEY_LAST_SEND_CODE_TIME = 'lastSendCodeTime';

/** Return how long has past during last code sending */
var getSendCodeDiff = function () {
  var lastSendCodeTime = utils.getCookies(COOKIE_KEY_LAST_SEND_CODE_TIME);
  if (lastSendCodeTime && lastSendCodeTime.length) {
    var now = (new Date()).getTime();
    var diff = now - lastSendCodeTime[0];
    return diff;
  } else {
    return -1;
  }
};

/** Determine whether can send code again */
var canSendCode = function (diff) {
  diff = diff ? diff : Math.floor(getSendCodeDiff() / 1000);
  return diff < 0 || diff >= 60;
};

/** Error toast */
var errToastTimeout = null;
var errToast = function (wrapper, contentWrapper, msg) {
  errToastTimeout && clearTimeout(errToastTimeout);
  
  msg = msg ? msg : '未知错误';
  
  $(contentWrapper).html(msg);
  $(wrapper).show();
  errToastTimeout = setTimeout(function () {
    $(wrapper).hide();
    clearTimeout(errToastTimeout);
    errToastTimeout = null;
  }, 2000);
};

/** Success toast */
var successToastTimeout = null;
var successToast = function (wrapper, contentWrapper, msg) {
  successToastTimeout && clearTimeout(successToastTimeout);
  
  msg = msg ? msg : '成功';
  
  $(contentWrapper).html(msg);
  $(wrapper).show();
  successToastTimeout = setTimeout(function () {
    $(wrapper).hide();
    clearTimeout(successToastTimeout);
    successToastTimeout = null;
  }, 2000);
};

/** Reister */
var register = function () {
  //no weixin userinfo found
  if (!userInfoObj || !userInfoObj.openid) {
    errToast($('#err-toast'), $('#err-toast-content'), '缺少微信账号信息，请刷新重试');
    return;
  }
  
  var checkResult = '';
  var userName = $.trim($('#register-name').val());
  if (!userName) {
    checkResult += '请输入姓名';
  } else if (userName.length > 10) {
    checkResult += '姓名不能超过10个汉字或字符';
  }
  var phone = $.trim($('#register-tel').val());
  if (!phone) {
    checkResult && (checkResult += '<br>');
    checkResult += '请输入手机号';
  } else if (!/^1[0-9]{10}$/.test(phone)) {
    checkResult && (checkResult += '<br>');
    checkResult += '请输入合法的11位手机号';
  }
  var code = $.trim($('#register-code').val());
  if (!code) {
    checkResult && (checkResult += '<br>');
    checkResult += '请输入验证码';
  } else if (code.length != 4) {
    checkResult && (checkResult += '<br>');
    checkResult += '请输入4位验证码';
  }
  var tag = $.trim($('#register-tag').val());
  
  if (checkResult) {
    // something error
    errToast($('#err-toast'), $('#err-toast-content'), checkResult);
  } else {
    // request to check the code
    $.ajax({
      type: 'post',
      url: 'register',
      data: {
        openId: userInfoObj.openid,
        userName: userName,
        phone: phone,
        avatar: userInfoObj.headimgurl,
        code: code,
        tag: tag
      },
      success: function (data) {
        try {
          var dataObj = JSON.parse(data);
          if (dataObj.code == 0) {
            // success
            successToast($('#success-toast'), $('#success-toast-content'), dataObj.msg);
              //没有抽过奖
              setTimeout(function () {
                location.href = 'lucky.html?openid=' + userInfoObj.openid;
              }, 2000);                        
            
          } else {
            // error
            errToast($('#err-toast'), $('#err-toast-content'), dataObj.msg);
          }
        } catch (e) {
          errToast($('#err-toast'), $('#err-toast-content'), JSON.stringify(e));
        }
      },
      error: function (data, textStatus) {
        errToast($('#err-toast'), $('#err-toast-content'), textStatus || data.statusText);
      }
    });
  }
};

/** 标签 */
var TAGS = [ "长跑牛人", "健身大咖", "瑜伽狂人", "游泳飞鱼", "打球高手", "K歌之王", "素食主义", "养生控", "乐天派", "开心果" ];
/** 标签说明 */
var TAG_COMMENTS = [
  "跑步呢，速度不重要，为健康，跑起来，越跑越开心",
  "我有人鱼线、马甲线，还有8块腹肌，你有么？",
  "我不是在练瑜伽，就是在去练瑜伽的路上",
  "好身体，游出来，且游且健康",
  "球动，我动，生命在于运动",
  "我唱的不是歌，我在锻炼我的肺活量",
  "别人一口一口吃成个胖子，我一口一口吃出健康美丽",
  "无养生，不生活，逆生长，好体质，就是我",
  "好身体，好心态，正能量，好运自然来",
  "不断制造笑点，人人都开心，把生活过成段子"
];
var TAGS_PLUS_COMMENTS = {
    "长跑牛人":"跑步呢，速度不重要，为健康，跑起来，越跑越开心",
    "健身大咖":"我有人鱼线、马甲线，还有8块腹肌，你有么？",
    "瑜伽狂人":"我不是在练瑜伽，就是在去练瑜伽的路上",
    "游泳飞鱼":"好身体，游出来，且游且健康",
    "打球高手":"球动，我动，生命在于运动",
    "K歌之王":"我唱的不是歌，我在锻炼我的肺活量",
    "素食主义":"别人一口一口吃成个胖子，我一口一口吃出健康美丽",
    "养生控":"无养生，不生活，逆生长，好体质，就是我",
    "乐天派":"好身体，好心态，正能量，好运自然来",
    "开心果":"不断制造笑点，人人都开心，把生活过成段子"
};

/** update user info */
var updateUserInfo = function () {
  if (!userInfoObj) {
    return;
  }
  userInfoObj.avatar && $('#lucky-info-avatar') && $('#lucky-info-avatar').attr('src', userInfoObj.avatar);
  userInfoObj.userName && $('#user-name') && $('#user-name').html(userInfoObj.userName);
  if (userInfoObj.tag && $('#info-tag')) {
    if (TAG_COMMENTS && TAG_COMMENTS.length) {
      $('#info-tag').html(TAG_COMMENTS[parseInt(userInfoObj.tag) % TAG_COMMENTS.length]);
    } else {
      $('#info-tag').html('跑步呢，速度不重要，为健康，跑起来，越跑越开心');
    }
  }
};

/** Set whether to show the lucky area or not */
var initLuckyWrapper = function () {
  if (!userInfoObj) {
    return;
  }

  if (userInfoObj.lucky) {
    // has drawed a lucky before
    if (userInfoObj.level == 0 || userInfoObj.level == 1 || (userInfoObj.level == 2 && userInfoObj.status == 1)) {
      $('#result-5') && $('#result-5').remove();
      if (swiper) {
        swiper.update();
      } else {
        swiper = new Swiper('.swiper-container', {
          direction: 'vertical',
          mousewheelControl: true,
          watchSlidesProgress: true,
        });
      }
      return;
    }
  }
  initLuckyListeners();
};

var barTouchStart = {};
var daltPoint = { x : 0, y : 0 };
var imgHeight = 60;
var barY = -10;
var luckyBar = null;
var drawing = false;
var drawed = false;
/** init listeners of lucky page */
var initLuckyListeners = function () {
  if (!luckyBar) luckyBar = document.getElementById('lucky-bar');
  if (!luckyBar) return;
  luckyBar.addEventListener('touchstart', function (e) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    var touch = e.touches && e.touches[0] || e.targetTouches && e.targetTouches[0];
    barTouchStart.x = touch.clientX;
    barTouchStart.y = touch.clientY;
  }, false);
  
  luckyBar.addEventListener('touchmove', function (e) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    var touch = e.touches && e.touches[0] || e.targetTouches && e.targetTouches[0];
    daltPoint = {
      x: touch.clientX - barTouchStart.x,
      y: touch.clientY - barTouchStart.y
    };
    if (daltPoint.y > 0 && daltPoint.y < 30) {
      barY = -10 + daltPoint.y;
      luckyBar.style.top = barY + 'px';
    }
  }, false);
  
  luckyBar.addEventListener('touchend', function (e) {
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    if (barY >= 5) {
      if (!drawing) {
        if (drawed) {
          errToast($('#err-toast'), $('#err-toast-content'), '每人仅有一次抽奖机会哦~');
        } else {
          drawing = true;
          setTimeout('hideTicket(0)', 1);
          startDraw();
        }
      }
      resetBar(barY);
    }
  }, false);
};

var resetBar = function (y) {
  luckyBar.style.top = y + 'px';
  if (y > -10) {
    setTimeout('resetBar(' + (y - 1) + ')', 1);
  }
};

var luckyTicket = null;
var hideTicket = function (y) {
  if (!luckyTicket) luckyTicket = document.getElementById('lucky-ticket');
  if (!luckyTicket) return;
  luckyTicket.style.marginTop = y + 'px';
  if (y > -80) {
    setTimeout('hideTicket(' + (y - 1) + ')', 1);
  }
};

var showTicket = function (y) {
  if (!luckyTicket) luckyTicket = document.getElementById('lucky-ticket');
  if (!luckyTicket) return;
  luckyTicket.style.marginTop = y + 'px';
  if (y < 0) {
    setTimeout('showTicket(' + (y + 1) + ')', 5);
  } else {
    drawing = false;
    if (drawedLuckyLevel == 0 || drawedLuckyLevel == 1) { // 一等奖或者二等奖
      successToast($('#success-toast'), $('#success-toast-content'), '工作人员将于7个工作日内与您联系');
    } else if (drawedLuckyLevel == 2) { // 三等奖
      successToast($('#success-toast'), $('#success-toast-content'), '跳转至领票界面');
      drawed = true;
      $.ajax({
        type: 'get',
        url: 'getTicketInfo',
        data: {openId: userInfoObj.openId},
        success: function (data) {
          try {
            var dataObj = JSON.parse(data);
            if (dataObj.code == 0) {
              wx.addCard({
                cardList: [{
                  cardId: dataObj.body.cardId,
                  cardExt: JSON.stringify({
                    code:dataObj.body.code,
                    timestamp:dataObj.body.timestamp,
                    nonce_str:dataObj.body.nonceStr,                                                 
                    signature:dataObj.body.signature
                  })
                }], // 需要添加的卡券列表
                success: function (res) {
                  var cardList = res.cardList;// 添加的卡券列表信息
                  drawed = true;
                  // 修改抽奖状态
                  if (userInfoObj) {
                    $.ajax({
                      type: 'get',
                      url: 'cardAdded',
                      data: { openId: userInfoObj.openId }
                    });
                  }
                }
              });
            } else {
              errToast($('#err-toast'), $('#err-toast-content'), dataObj.msg);
            }
          } catch (e) {
            errToast($('#err-toast'), $('#err-toast-content'), JSON.stringify(e));
          }
        },
        error: function (textStatus) {
          errToast($('#err-toast'), $('#err-toast-content'), textStatus || data.statusText);
        }
      });

    } else {// 四等奖
      successToast($('#success-toast'), $('#success-toast-content'), '谢谢参与');
    }
  }
};

var wheelOne, wheelTwo, wheelThree;
var stoppedWheel = 0;
var wheelIntervalOne = null, wheelIntervalTwo = null, wheelIntervalThree = null;
var drawedLuckyLevel = -1;
var stopWheelY = [
  [0, -2 * imgHeight, -1 * imgHeight], [-1 * imgHeight, 0, -2 * imgHeight], [-2 * imgHeight, -1 * imgHeight, 0]
];
var threeSecondsEnough = false;
var wheelCanStop = false;

var startDraw = function () {
  if (!userInfoObj) {
    return;
  }
  
  wheelOne = { wheel: document.getElementById('lucky-wheel-0'), y : -3 * imgHeight };
  wheelTwo = { wheel: document.getElementById('lucky-wheel-1'), y : -3 * imgHeight };
  wheelThree = { wheel: document.getElementById('lucky-wheel-2'), y : -3 * imgHeight };
  
  // start to run the wheels
  setTimeout(function () {
    runWheel(wheelOne);
  }, 0);
  
  setTimeout(function () {
    runWheel(wheelTwo);
  }, 200);

  setTimeout(function () {
    runWheel(wheelThree);
  }, 400);
  
  stoppedWheel = 0;
  
  // let the wheel run at least 3 seconds
  threeSecondsEnough = false;
  setTimeout(function () {
    threeSecondsEnough = true;
  }, 3000);
  
  
  // request the server to draw a lucky
  $.ajax({
    type: 'get',
    url: 'draw',
    data: {
      openId: userInfoObj.openId
    },
    success: function (data) {
      try {
        var dataObj = JSON.parse(data);
        if (dataObj.code == 0 || (dataObj.body && dataObj.body.hasDrawed && dataObj.body.status == 0 )) {
          var bodyObj = dataObj.body;
          if (bodyObj.level == 0 || bodyObj.level == 1 || bodyObj.level == 2 ||bodyObj.level == 3) {
            drawedLuckyLevel = bodyObj.level;
           
            setTimeout(function () {
              !luckyTicket && (luckyTicket = document.getElementById('lucky-ticket'));
              luckyTicket.src = 'img/lucky-ticket-' + bodyObj.level + '.png';
              wheelOne.stopY = stopWheelY[0][bodyObj.level];
              wheelTwo.stopY = stopWheelY[1][bodyObj.level];
              wheelThree.stopY = stopWheelY[2][bodyObj.level];
              wheelCanStop = true;
              drawed = true;
              if (bodyObj.level == 2) {
                // 显示领票界面
                // 在showTicket中显示
                // 弹出 输入框，要求用户输入邮箱
                
              }
            }, 500);
          } else if(bodyObj.level == -1){//三等奖尚未准备好
            errToast($('#err-toast'), $('#err-toast-content'), '不好，服务器跑路了，小劲去给您追回来，您稍后再来吧');
            wheelOne.stopY = stopWheelY[0][0];
            wheelTwo.stopY = stopWheelY[1][1];
            wheelThree.stopY = stopWheelY[2][2];
            wheelCanStop = true;
            drawed = false;
            threeSecondsEnough = true;
          }
            else {
            errToast($('#err-toast'), $('#err-toast-content'), '无效的抽奖结果：' + level);
            wheelOne.stopY = stopWheelY[0][0];
            wheelTwo.stopY = stopWheelY[1][1];
            wheelThree.stopY = stopWheelY[2][2];
            wheelCanStop = true;
            drawed = false;
            threeSecondsEnough = true;
          }
        } else {
          if (dataObj.body) {
            if (dataObj.body.noOpenId || dataObj.body.notRegistered) {
              errToast($('#err-toast'), $('#err-toast-content'), dataObj.msg);
              // no openid found, or not registered
              // redirect to oauth page and then redirect to index page
              setTimeout(redirectToOauth, 2000);
            } else if (dataObj.body.hasDrawed) {//该用户已经抽过奖了
              if (!dataObj.body.level) {
                wheelOne.stopY = stopWheelY[0][0];
                wheelTwo.stopY = stopWheelY[1][1];
                wheelThree.stopY = stopWheelY[2][2];
                wheelCanStop = true;
                drawed = true;
                threeSecondsEnough = true;
              } else {
                if (dataObj.body.level == 0 || dataObj.body.level == 1) {//一等奖或者二等奖
                  wheelOne.stopY = stopWheelY[0][0];
                  wheelTwo.stopY = stopWheelY[1][1];
                  wheelThree.stopY = stopWheelY[2][2];
                  wheelCanStop = true;
                  drawed = true;
                  threeSecondsEnough = true;
                  errToast($('#err-toast'), $('#err-toast-content'), dataObj.msg);
                } else {
                  if (dataObj.body.status == 0) {
                    wheelOne.stopY = stopWheelY[0][2];
                    wheelTwo.stopY = stopWheelY[1][2];
                    wheelThree.stopY = stopWheelY[2][2];
                    wheelCanStop = true;
                    drawed = true;
                    threeSecondsEnough = false;
                    !luckyTicket && (luckyTicket = document.getElementById('lucky-ticket'));
                    luckyTicket.src = 'img/lucky-ticket-' + dataObj.body.level + '.png';
                    // 显示领票界面
                    // 在showTicket中显示
                    successToast($('#success-toast'), $('#success-toast-content'), '您已经抽过奖喽');
                  } else {
                    wheelOne.stopY = stopWheelY[0][0];
                    wheelTwo.stopY = stopWheelY[1][1];
                    wheelThree.stopY = stopWheelY[2][2];
                    wheelCanStop = true;
                    drawed = true;
                    threeSecondsEnough = true;
                    errToast($('#err-toast'), $('#err-toast-content'), dataObj.msg);
                  }
                }
              }
            }
          }
        }
      } catch (e) {
        errToast($('#err-toast'), $('#err-toast-content'), JSON.stringify(e));
        wheelOne.stopY = stopWheelY[0][0];
        wheelTwo.stopY = stopWheelY[1][1];
        wheelThree.stopY = stopWheelY[2][2];
        wheelCanStop = true;
        drawed = false;
        threeSecondsEnough = true;
      }
    },
    error: function (data, textStatus) {
      errToast($('#err-toast'), $('#err-toast-content'), textStatus || data.statusText);
      wheelOne.stopY = stopWheelY[0][0];
      wheelTwo.stopY = stopWheelY[1][1];
      wheelThree.stopY = stopWheelY[2][2];
      wheelCanStop = true;
      drawed = false;
      threeSecondsEnough = true;
    }
  });
};

var runWheel = function (wheelObj) {
  wheelObj.y += 1;
  wheelObj.wheel.style.marginTop = wheelObj.y + 'px';
  if (wheelObj.y > 0) {
    wheelObj.y = -180;
  }
  
  if (!wheelCanStop || !threeSecondsEnough) {
    // the wheel cannot stop or they has not run for 3 seconds
    setTimeout(function () {
      runWheel(wheelObj);
    }, 1);
  } else {
    if (wheelObj.y == wheelObj.stopY) {
      wheelObj.wheel.style.marginTop = wheelObj.stopY + 'px';
      ++stoppedWheel;
      if (stoppedWheel == 3) {
        setTimeout('showTicket(-80)', 500);
      }
    } else {
      setTimeout(function () {
        runWheel(wheelObj);
      }, 1);
    }
  }
};

var showShareWrapper = function () {
  $('#share-wrapper') && $('#share-wrapper').show();
};

$(function(){
  $('#share-wrapper').click(function () {
    $('#share-wrapper').hide();
  });
});

var foodOrderWrapper = null;
var initCitiesScroll = function () {
  var citiesWrapper = document.getElementById('cities-wrapper');
  var citiesInner = document.getElementById('cities-inner');
  foodOrderWrapper = document.getElementById('food-order-wrapper');
  
  var wrapperHeight = citiesWrapper.offsetHeight;
  var innerHeight = citiesInner.offsetHeight;
  var marginTop = 0;
  var oldMarginTop = 0;
  var minMarginTop = wrapperHeight - innerHeight;
  
  if (innerHeight > wrapperHeight) {
    var startY = null;
    citiesInner.addEventListener('touchstart', function (e) {
      // e.preventDefault && e.preventDefault();
      // e.stopPropagation && e.stopPropagation();
     var touches = e.touches[0] || e.targetTouches[0];
      startY = touches.clientY;
      oldMarginTop = marginTop;
    });
    citiesInner.addEventListener('touchmove', function (e) {
      var daltY = (e.touches[0] || e.targetTouches[0]).clientY - startY;
      daltY = Math.floor(daltY / 2);
      if (daltY < 0) { // up
        if (oldMarginTop > minMarginTop) {
          e.preventDefault && e.preventDefault();
          e.stopPropagation && e.stopPropagation();
          if (marginTop >= minMarginTop) {
            marginTop = oldMarginTop + daltY;
            if (marginTop < minMarginTop) {
              marginTop = minMarginTop;
            }
            citiesInner.style.marginTop = marginTop + 'px';
          }
        }
      } else { // down
      if (oldMarginTop < 0) {
          e.preventDefault && e.preventDefault();
          e.stopPropagation && e.stopPropagation();
          if (marginTop < 0) {
            marginTop = oldMarginTop + daltY;
            if (marginTop > 0) {
              marginTop = 0;
            }
            citiesInner.style.marginTop = marginTop + 'px';
          }
       }
      }
    });
  }
};

var links = null;
var showFoodOrderWrapper = function (city) {
  if (!foodOrderWrapper) {
    foodOrderWrapper = document.getElementById('food-order-wrapper');
  }
  
  if (!foodOrderWrapper) return;
  
  foodOrderWrapper.style.display = 'block';
  var citiesWrapper = document.getElementById('cities-wrapper');
  citiesWrapper.style.display = "none";
  
  links = LINK[city];
  console.log("links="+JSON.stringify(links));
  mui("#food-order-wrapper").on('tap', 'a', function(event){
  		var id = this.getAttribute("id");
  		console.log("id="+id);
  		location.href = links[id+""];
  });
};

var closeFoodOrderWrapper = function () {
  if (!foodOrderWrapper) {
    foodOrderWrapper = document.getElementById('food-order-wrapper');
  }
  
  if (!foodOrderWrapper) return;
  
  foodOrderWrapper.style.display = 'none';
  var citiesWrapper = document.getElementById('cities-wrapper');
  citiesWrapper.style.display = "block";
};

var ajaxGet = function (page, params) {
  !page && (page = 1);
  var key = $.trim($('#query-rank-input').val());
  ajaxRank(key, page);
};

/**
 * 获取排行榜
 */
var ajaxRank = function(key, page) {
  $("#load-rank-wrapper").show();
  $.ajax({
    type: 'get',
    url: 'rank',
    data: { queryKey : key, currentPage : page },
    success: function (data) {
      try {
        var ajaxResult = JSON.parse(data);
        if (ajaxResult.code == 0 && ajaxResult.body && ajaxResult.body.result) {
          $('#rank-result-wrapper').html('');
          $('#rank-result-pagination').html('');
          var result = JSON.parse(ajaxResult.body.result);
          var queryResult = JSON.parse(result.ajaxQueryResult);
          var len = queryResult.length;
          if (len) {
            for (var i=0, len=queryResult.length; i<len; ++i) {
              var user = queryResult[i];
              var str = '' +
                '<div class="rank-result-item" onclick="readUserInfo(\'' + user.openId + '\')">' +
                  '<div class="rank-result-avatar-wrapper"><img src="' + (user.avatar ? user.avatar : 'img/lucky-info-default-avatar.png') + '" class="rank-result-avatar" /></div>' +
                  '<div class="rank-result-info-wrapper">' +
                    '<div>姓名：' + user.userName + '</div>' +
                    '<div>票数：' + user.support + '</div>' +
                    '<div>排名：第' + (user.rank + 1) + '名</div>' +
                  '</div>' +
                  (user.rank == 0 ? '<div class="rank-star-0"><img src="img/rank-star-0.png"/></div>' : '') +
                '</div>';
              $('#rank-result-wrapper').append($(str));
            }

            var paginationStr = '<ul class="pagination">' +
              result.firstPage +
              result.previousPage +
              result.normalPage +
              result.nextPage + 
              result.lastPage + '</ul>';
            $('#rank-result-pagination').append(paginationStr);
          } else {
            $('#rank-result-wrapper').append('<div class="rank-result-error">没有检索到任何结果</div>');
          }
        } else {
          errToast($('#err-toast'), $('#err-toast-content'), ajaxResult.msg);
        }
      } catch (e) {
        errToast($('#err-toast'), $('#err-toast-content'), JSON.stringify(e));
      }
      $("#load-rank-wrapper").hide();
    },
    error: function (data, textStatus) {
      
    }
  });
};

var readUserInfo = function (openId) {
  location.href = 'support.html?candidate=' + openId;
};

var jumpToNext = function () {
  swiper && swiper.slideNext();
};

var jumpToPrev = function () {
  swiper && swiper.slidePrev();
};

var linkTo = function(index) {
  if(index == 0)
    location.href = 'http://mp.weixin.qq.com/s?__biz=MzA3NTIwNDc1OQ==&mid=2650070808&idx=1&sn=7b4f96bb2742ecf168964b7c2b47979e&scene=1&srcid=0705f2N3jVyOWXazTQlLmg3f&from=singlemessage&isappinstalled=0#wechat_redirect';
  else if(index == 1)
    location.href = 'http://mp.weixin.qq.com/s?__biz=MzA3NTIwNDc1OQ==&mid=2650070810&idx=1&sn=ea9bc0bbc7855a99a4e90cc18deacd18&scene=1&srcid=0705aTwHeZTjboQgZZJxp5nd&from=singlemessage&isappinstalled=0#wechat_redirect';
  else if(index == 2)
    location.href = 'http://mp.weixin.qq.com/s?__biz=MzA3NTIwNDc1OQ==&mid=2650070812&idx=1&sn=eb8a414f3ede7097aaaccb9a79119e4f&scene=0#wechat_redirect';
  else if(index == 100){
    location.href = 'http://www.jingpai.com/';
  }
};

var media = document.getElementById("media");
var control = document.getElementById("audio_btn");
var playorPause = function(){
  if(!media)
    media = document.getElementById("media");
  if(media.paused){
    media.play();
    $("#audio_btn").addClass('rotate');   
  }else{
    media.pause();
    $("#audio_btn").removeClass('rotate');
  }
    
};

var jumpToSwipe = function(i){
  if($('#result-5'))
    swiper && swiper.slideTo(i);
  else
    swiper && swiper.slideTo(i-1);
  
};